<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.nj9you.wxpay.model.PayParams"%>
<%@ page import="com.nj9you.wxpay.service.OrderService"%>
<%@ page import="com.nj9you.wxpay.service.impl.OrderServiceImpl"%>
<%@ page import="com.nj9you.wxpay.config.WXProperty"%>
<%@ page import="org.apache.log4j.Logger" %>
<%!
        String generateResult(boolean success, String data) {
            StringBuilder builder = new StringBuilder();
            builder.append("{");
            builder.append("\"resultStatus\"").append(":").append(success ? "\"SUCCESS\"" : "\"FAIL\"").append(",");
            builder.append("\"data\"").append(":").append(data);
            builder.append("}");
            return builder.toString();
        }
%>
<%
        Logger logger = Logger.getLogger("jsp_request_payinfo");
        request.setCharacterEncoding("UTF-8");
        StringBuilder builder = new StringBuilder();
        Enumeration<String> names = request.getParameterNames();
        while(names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            builder.append(",").append(name).append("=").append(value);
        }
        builder.deleteCharAt(0);
        logger.debug("params : [" + builder.toString() + "]");
        // 支持跨域请求
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        String subject = request.getParameter("subject");
        String orderId = request.getParameter("order_id");
        String amount = request.getParameter("amount");
        String openId = request.getParameter("extension"); // 获取微信的openid
        String notifyUrl = WXProperty.getNotifyUrl(request);
        OrderService service = new OrderServiceImpl();
        PayParams payParams = service.generatePayParams(subject, orderId, amount, openId, notifyUrl);
        out.clearBuffer();
        if (payParams != null) {
            String prepayId = payParams.getPrepayId();
            if (prepayId != null && !prepayId.trim().equals("")) {
                out.print(generateResult(true, payParams.toJson()));
            } else {
                out.print(generateResult(false, payParams.getError()));
            }
        } else {
            out.print(generateResult(false, null));
        }
%>